package com.warrantyhotel.android.ui;

import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.digest.DigestUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.CountryTable;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.LanguageTable;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.StateTable;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.service.UpdateIntentService;
import com.warrantyhotel.android.util.DateUtis;
import com.warrantyhotel.android.util.DetachableResultReceiver;
import com.warrantyhotel.android.util.DetachableResultReceiver.Receiver;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler.AsyncQueryListener;
import com.warrantyhotel.android.util.ToastUtil;

public class RegistrationActivity extends Activity implements Receiver, OnItemSelectedListener, AsyncQueryListener {

	private static final String TAG = RegistrationActivity.class.getSimpleName();

	private NotifyingAsyncQueryHandler mHandler;

	private LinearLayout llPersonalInfo;
	private LinearLayout llAddress;
	private static SharedPreferences prefs;

	private Spinner spnAddresCountrySpinner;
	private Spinner spnAddresStateSpinner;
	private Spinner spnGenderSpinner;
	private Spinner spnLanguageSpinner;

	private EditText edtUsername;
	private EditText edtPassword;
	private EditText edtConfirmPassword;
	private EditText edtAddress;
	private EditText edtZipCode;
	private EditText edtCity;
	private TextView txtMobilePrefix;
	private TextView txtPhonePrefix;
	private EditText edtPhone;
	private EditText edtMobile;
	private EditText edtFirstName;
	private EditText edtSecondName;

	private TextView mobile_prefix;
	private TextView phone_prefix;

	private SimpleCursorAdapter countriesAdapter;
	private SimpleCursorAdapter stateAdapter;
	private SimpleCursorAdapter languageAdapter;
	private ArrayAdapter<CharSequence> adapterGender;

	private String country;
	private boolean isCountrySelected = false;
	public static final String FAKE_ID = "AAA";

	private int stateId;

	private Boolean gender;

	private boolean isLanguageSelect = false;
	private int languageID;

	private static final int DATE_DIALOG_ID = 0;
	private Calendar calendar;
	private Button birthDate;
	private WarrantyApplication app;

	private ProgressDialog progress;
	private DetachableResultReceiver receiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register_page);

		app = (WarrantyApplication) getApplication();
		prefs = PreferenceManager.getDefaultSharedPreferences(this);

		llPersonalInfo = (LinearLayout) findViewById(R.id.personal_information_items);
		llAddress = (LinearLayout) findViewById(R.id.address_items);
		edtAddress = (EditText) findViewById(R.id.address_address);
		edtZipCode = (EditText) findViewById(R.id.address_zip_code);
		edtCity = (EditText) findViewById(R.id.address_city);
		txtMobilePrefix = (TextView) findViewById(R.id.address_mobile_prefix);
		txtPhonePrefix = (TextView) findViewById(R.id.address_phone_prefix);
		edtPhone = (EditText) findViewById(R.id.address_phone);
		edtMobile = (EditText) findViewById(R.id.address_mobile);
		edtUsername = (EditText) findViewById(R.id.username);
		edtPassword = (EditText) findViewById(R.id.password);
		edtConfirmPassword = (EditText) findViewById(R.id.confirm_password);
		edtFirstName = (EditText) findViewById(R.id.personal_information_first_name);
		edtSecondName = (EditText) findViewById(R.id.personal_information_second_name);
		birthDate = (Button) findViewById(R.id.set_birth_date);
		birthDate.setTag(null);

		mobile_prefix = (TextView) findViewById(R.id.address_mobile_prefix);
		phone_prefix = (TextView) findViewById(R.id.address_phone_prefix);

		spnAddresCountrySpinner = (Spinner) findViewById(R.id.address_country_spinner);
		spnAddresCountrySpinner.setOnItemSelectedListener(this);
		spnAddresStateSpinner = (Spinner) findViewById(R.id.address_state_spinner);
		spnAddresStateSpinner.setOnItemSelectedListener(this);
		spnGenderSpinner = (Spinner) findViewById(R.id.gender_spinner);
		spnLanguageSpinner = (Spinner) findViewById(R.id.language_spinner);
		spnLanguageSpinner.setOnItemSelectedListener(this);

		adapterGender = ArrayAdapter.createFromResource(this, R.array.gender_array, android.R.layout.simple_spinner_item);

		adapterGender.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnGenderSpinner.setAdapter(adapterGender);

		// TODO

		spnGenderSpinner.setOnItemSelectedListener(this);

		calendar = Calendar.getInstance();

		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);

		// query for retrieving data for spinners from db
		coutryQueryRetrieving();
		languageQueryRetrieving();

		// Update state list
		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);
		executeUpdateQueries();

	}

	private void executeUpdateQueries() {
		// State country list
		Intent updateIntent = new Intent(Intent.ACTION_SYNC, StateTable.CONTENT_URI, this, UpdateIntentService.class);
		updateIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
		updateIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.SELECT_STATE_TABLE);
		startService(updateIntent);

		// Update country list
		updateIntent = new Intent(Intent.ACTION_SYNC, CountryTable.CONTENT_URI, this, UpdateIntentService.class);
		updateIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
		updateIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.SELCET_COUNTRY_TABLE);
		startService(updateIntent);

		// Update language list
		updateIntent = new Intent(Intent.ACTION_SYNC, LanguageTable.CONTENT_URI, this, UpdateIntentService.class);
		updateIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
		updateIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.SELECT_LANGUAGE_TABLE);
		startService(updateIntent);
	}

	// query for retrieving Countries
	private void coutryQueryRetrieving() {

		ContentValues values = new ContentValues();
		values.put(CountryTable.NAME_HACK, FAKE_ID);
		values.put(CountryTable.COUNTRY_ID, FAKE_ID);
		values.put(CountryTable.NAME, getString(R.string.select_country));
		getContentResolver().insert(CountryTable.CONTENT_URI, values);

		String[] projectionCountry = { CountryTable._ID, CountryTable.NAME, CountryTable.COUNTRY_ID };
		mHandler.startQuery(QueriesCodes.SELCET_COUNTRY_TABLE, CountryTable.CONTENT_URI, projectionCountry, null, null, null);

	}

	// query for retrieving Language
	private void languageQueryRetrieving() {
		ContentValues values = new ContentValues();
		values.put(LanguageTable.LANGUAGE_ID, 0);
		values.put(LanguageTable.ENGLISH_NAME, getString(R.string.select_language));
		getContentResolver().insert(LanguageTable.CONTENT_URI, values);
		// query for retrieving Language
		String[] projectionLanguage = { LanguageTable._ID, LanguageTable.LANGUAGE_ID, LanguageTable.ENGLISH_NAME };
		mHandler.startQuery(QueriesCodes.SELECT_LANGUAGE_TABLE, LanguageTable.CONTENT_URI, projectionLanguage, null, null, LanguageTable.LANGUAGE_ID);
	}

	// query for retrieving State
	private void stateQueryRetrieving(String countryId) {
		// ContentValues values = new ContentValues();
		// values.put(StateTable.STATE_ID, FAKE_ID);
		// values.put(StateTable.STATE_NAME, getString(R.string.select_state));
		// getContentResolver().insert(StateTable.CONTENT_URI, values);
		String[] projectionState = { StateTable._ID, StateTable.STATE_NAME, StateTable.STATE_ID, StateTable.COUNTRY_ID };
		mHandler.startQuery(QueriesCodes.SELECT_STATE_TABLE, StateTable.CONTENT_URI, projectionState, StateTable.COUNTRY_ID + "='" + countryId + "'", null,
				null);
	}

	// query for retrieving phone prefix
	private void phonePrefixQueryRetrieving(String countryId) {
		String[] projectionCountry = { CountryTable._ID, CountryTable.NAME, CountryTable.COUNTRY_ID, CountryTable.PHONE_PREFIX };
		mHandler.startQuery(QueriesCodes.SELECT_PHONE_PREFIX, CountryTable.CONTENT_URI, projectionCountry, CountryTable.COUNTRY_ID + " ='" + countryId + "'",
				null, null);
	}

	public void onRegisterClick(View view) {

		if (!validate(edtUsername) || !isEmailValid(edtUsername.getText().toString().trim()) || !validate(edtPassword) || !validate(edtConfirmPassword)) {
			ToastUtil.showText(this, getString(R.string.validate_error));
			return;
		} else if (!edtPassword.getText().toString().trim().equals(edtConfirmPassword.getText().toString().trim())) {
			ToastUtil.showText(this, getString(R.string.passwords_are_not_equals));
			return;
		} else {
			// registration
			progress = ProgressDialog.show(this, getString(R.string.loading), getString(R.string.please_wait), true, false);

			receiver = new DetachableResultReceiver(new Handler());
			receiver.setReceiver(this);
			Intent loginIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);
			loginIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
			loginIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.DO_REGISTRATION);

			JSONObject jsonRegistration = new JSONObject();
			try {
				jsonRegistration.put(Keys.jsNewAccountCode, Keys.NewAccountCodeValue);
				jsonRegistration.put(Keys.jsNewIdentityEmail, edtUsername.getText().toString().trim());
				jsonRegistration.put(Keys.jsMd5Password, DigestUtils.md5Hex(edtConfirmPassword.getText().toString().trim()));
				// address street
				String value = edtAddress.getText().toString().trim();
				if (null != value && !TextUtils.isEmpty(value)) {
					jsonRegistration.put(Keys._addressStreet, value);
				}
				// zip code
				value = edtZipCode.getText().toString().trim();
				if (null != value && !TextUtils.isEmpty(value)) {
					jsonRegistration.put(Keys._addressPostalCode, value);
				}
				// City
				value = edtCity.getText().toString().trim();
				if (null != value && !TextUtils.isEmpty(value)) {
					jsonRegistration.put(Keys._addressCity, value);
				}
				// mobile phone prefix
				value = txtMobilePrefix.getText().toString().trim();
				if (null != value && !TextUtils.isEmpty(value)) {
					jsonRegistration.put(Keys._mobilePhonePrefix, value);
				}
				// phone prefix
				value = txtPhonePrefix.getText().toString().trim();
				if (null != value && !TextUtils.isEmpty(value)) {
					jsonRegistration.put(Keys._phonePrefix, value);
				}
				// mobile
				value = edtMobile.getText().toString().trim();
				if (null != value && !TextUtils.isEmpty(value)) {
					jsonRegistration.put(Keys._mobilePhone, value);
				}
				// phone
				value = edtPhone.getText().toString().trim();
				if (null != value && !TextUtils.isEmpty(value)) {
					jsonRegistration.put(Keys._phone, value);
				}

				// first name
				value = edtFirstName.getText().toString().trim();
				if (null != value && !TextUtils.isEmpty(value)) {
					jsonRegistration.put(Keys._firstName, value);
				}
				// second name
				value = edtSecondName.getText().toString().trim();
				if (null != value && !TextUtils.isEmpty(value)) {
					jsonRegistration.put(Keys._lastName, value);
				}

				// birth date
				Long date = (Long) birthDate.getTag();
				if (null != date)
					jsonRegistration.put(Keys._birthdate, DateUtis.decodeDate(date));

				// country
				if (isCountrySelected) {
					jsonRegistration.put(Keys._addressCountryID, country);
				}
				// state
				if (stateId != 0)
					jsonRegistration.put(Keys._addressStateID, stateId);
				// language
				if (isLanguageSelect && languageID != 0)
					jsonRegistration.put(Keys._languageId, languageID);
				// gender
//				if (isGenderSelected)
					jsonRegistration.put(Keys._gender, gender);

			} catch (JSONException e) {
				e.printStackTrace();
			}

			loginIntent.putExtra(Keys._jsregistrationObject, jsonRegistration.toString());
			startService(loginIntent);

		}

	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {

		switch (resultCode) {
		case UpdateIntentService.STATUS_RUNNING:
			// do nothing
			break;
		case UpdateIntentService.STATUS_ERROR:
			// ToastUtil.showText(getApplicationContext(),
			// resultData.getString(UpdateIntentService.ERROR_MESSAGE));
			if (progress != null)
				progress.dismiss();
			break;

		case UpdateIntentService.STATUS_FINISHED:
			// Require after successful update
			switch (resultData.getInt(Keys.actionIdentificator)) {
			case QueriesCodes.SELCET_COUNTRY_TABLE:
				coutryQueryRetrieving();
				// stackUpdateOperations.pop();
				break;
			case QueriesCodes.SELECT_LANGUAGE_TABLE:
				languageQueryRetrieving();
				if (progress != null)
					progress.dismiss();
				// stackUpdateOperations.pop();
				break;
			case QueriesCodes.DO_REGISTRATION:
				if (resultData.containsKey(Keys._isRegistrationSuccess)) {
					if (progress != null)
						progress.dismiss();
					if (resultData.getBoolean(Keys._isRegistrationSuccess)) {

						Intent loginIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);
						loginIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
						loginIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.DO_LOGIN);
						loginIntent.putExtra(Keys._username, edtUsername.getText().toString().trim());
						loginIntent.putExtra(Keys._password, edtPassword.getText().toString().trim());
						loginIntent.putExtra(Keys._remembeMe, true);
						startService(loginIntent);

					} else {
						ToastUtil.showText(getApplicationContext(), resultData.getString(Keys._message));
					}
				}
			case QueriesCodes.SELECT_STATE_TABLE:
				break;
			default:
				break;
			}

			if (resultData.containsKey(Keys._isLoginSuccess) && resultData.getBoolean(Keys._isLoginSuccess)) {
				final Intent intent = new Intent(RegistrationActivity.this, HomeActivity.class);
				executeUpdateQueries();

				intent.putExtra(Keys._firstName, resultData.getString(Keys._firstName));
				intent.putExtra(Keys._lastName, resultData.getString(Keys._lastName));
				// executeUpdateQueries();

				final Editor edit = prefs.edit();

				edit.remove(Keys._firstName);
				edit.remove(Keys._lastName);

				// save user/pass
				edit.putString(Keys._cacheLogin, edtUsername.getText().toString().trim());
				edit.putString(Keys._cachePass, edtPassword.getText().toString().trim());
				edit.putString(Keys._firstName, resultData.getString(Keys._firstName));
				edit.putString(Keys._lastName, resultData.getString(Keys._lastName));
				edit.commit();

				startActivity(intent);
				finish();
				app.startExpireSession(resultData.getLong(Keys._session_time));

			} else if (resultData.containsKey(Keys._isLoginSuccess) && !resultData.getBoolean(Keys._isLoginSuccess)) {
				ToastUtil.showText(getApplicationContext(), getString(R.string.credential_error));
			}

			break;
		}

	}

	/**
	 * Change visibilty for subItems tab
	 * 
	 * @param view
	 */
	public void changeVisibility(View view) {
		ImageView imageView = null;
		View llTab = null;
		switch (view.getId()) {
		case R.id.personal_information_items_button:
			llTab = llPersonalInfo;
			imageView = (ImageView) findViewById(R.id.swither_image_2);
			break;
		case R.id.address_items_buttons:
			llTab = llAddress;
			imageView = (ImageView) findViewById(R.id.swither_image_1);
			break;
		default:
			break;
		}
		if (null != llTab) {
			llTab.setVisibility(convertVisibility(llTab.getVisibility()));
			imageView.setImageResource((llTab.getVisibility() == View.VISIBLE) ? R.drawable.arr_down : R.drawable.arr_right);
		}
	}

	/**
	 * Convert visibility from GONE to VISIBLE and opposite
	 */
	private int convertVisibility(int visibility) {
		return (visibility == View.VISIBLE) ? View.GONE : View.VISIBLE;
	}

	public void setBirthDate(View view) {
		showDialog(DATE_DIALOG_ID);
	}

	@Override
	public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
		/*
		 * On Country Item selected - creation new query for retrieving states
		 */
		// TODO
		if (adapterView.getAdapter().equals(countriesAdapter)) {
			String countryId = "";
			Cursor mCursor = countriesAdapter.getCursor();
			if (null != mCursor) {
				if (mCursor.moveToPosition(position)) {
					countryId = mCursor.getString(mCursor.getColumnIndex(CountryTable.COUNTRY_ID));
					country = countryId;
					if (FAKE_ID.equals(country)) {
						isCountrySelected = false;
						stateId = 0;
					} else {
						isCountrySelected = true;
					}
					// isCountrySelected = (FAKE_ID.equals(country)) ? false :
					// true;
				}
				Log.i(TAG, countryId + " " + country);
			}

			// query for retrieving phone prefix
			phonePrefixQueryRetrieving(countryId);

			// query for retrieving states
			stateQueryRetrieving(countryId);

		} else if (adapterView.getAdapter().equals(stateAdapter)) {
			Cursor mCursor = stateAdapter.getCursor();

			if (null != mCursor) {
				if (mCursor.moveToPosition(position)) {
					stateId = mCursor.getInt(mCursor.getColumnIndex(StateTable.STATE_ID));
				}
				Log.i(TAG, " " + stateId);
			}

		} else if (adapterView.getAdapter().equals(languageAdapter)) {
			Cursor mCursor = languageAdapter.getCursor();
			if (position == 0) {
				isLanguageSelect = false;
			} else if (null != mCursor) {
				isLanguageSelect = true;
				if (mCursor.moveToPosition(position)) {
					languageID = mCursor.getInt(mCursor.getColumnIndex(LanguageTable.LANGUAGE_ID));
					Log.i(TAG, " " + stateId);
				}
			}
		} else if (adapterView.getAdapter().equals(adapterGender)) {

			switch (position) {
//			case 0:
//				isGenderSelected = false;
//				break;
			case 0:
				gender = null;
//				isGenderSelected = true;
				break;
			case 1:
//				isGenderSelected = true;
				gender = true;
				break;
			case 2:
//				isGenderSelected = true;
				gender = false;
				break;
			default:
				break;
			}

		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch (token) {
		case QueriesCodes.SELCET_COUNTRY_TABLE:
			if (cursor != null) {
				startManagingCursor(cursor);
				// countryCursor = cursor;
				if (null == countriesAdapter) {
					// if db is empty
					if (cursor.getCount() == 0)
						progress = ProgressDialog.show(this, getString(R.string.loading), getString(R.string.please_wait), true, false);
					countriesAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] { CountryTable.NAME },
							new int[] { android.R.id.text1 });
					spnAddresCountrySpinner.setAdapter(countriesAdapter);
					countriesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				} else {
					countriesAdapter.changeCursor(cursor);
					countriesAdapter.notifyDataSetChanged();
				}
			}
			break;
		case QueriesCodes.SELECT_STATE_TABLE:
			if (cursor != null) {
				startManagingCursor(cursor);
				boolean state = (cursor.getCount() == 0) ? false : true;
				spnAddresStateSpinner.setEnabled(state);
				if (null == stateAdapter) {
					stateAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] { StateTable.STATE_NAME },
							new int[] { android.R.id.text1 });
					spnAddresStateSpinner.setAdapter(stateAdapter);
					stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				} else {
					stateAdapter.changeCursor(cursor);
					stateAdapter.notifyDataSetChanged();
				}
			}
			break;
		case QueriesCodes.SELECT_PHONE_PREFIX:
			if (cursor != null) {
				String phonePrefix = "";
				startManagingCursor(cursor);
				if (cursor.moveToFirst()) {
					phonePrefix = cursor.getString(cursor.getColumnIndex(CountryTable.PHONE_PREFIX));
				}
				cursor.close();
				mobile_prefix.setText(phonePrefix);
				phone_prefix.setText(phonePrefix);
			}
			break;
		case QueriesCodes.SELECT_LANGUAGE_TABLE:
			if (cursor != null) {
				startManagingCursor(cursor);
				if (null == languageAdapter) {
					languageAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] { LanguageTable.ENGLISH_NAME },
							new int[] { android.R.id.text1 });
					spnLanguageSpinner.setAdapter(languageAdapter);
					languageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				} else {
					languageAdapter.changeCursor(cursor);
					languageAdapter.notifyDataSetChanged();
				}

			}
			break;
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			// return new DatePickerDialog(this, mDateSetListener,
			// calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
			// calendar.get(Calendar.DAY_OF_MONTH));
			return new DatePickerDialog(this, mDateSetListener, 1980, 0, 1);
		}
		return null;
	}

	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			calendar.set(Calendar.YEAR, year);
			calendar.set(Calendar.MONTH, monthOfYear);
			calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			// birthDate.setText(DateFormat.format(Keys.dateFormat, calendar));
			// birthDate.setTag(calendar.getTimeInMillis());
			if (calendar.getTimeInMillis() > System.currentTimeMillis()) {
				ToastUtil.showText(getApplicationContext(), getString(R.string.invalid_date));
			} else {
				birthDate.setText(DateFormat.format(Keys.dateFormat, calendar));
				birthDate.setTag(calendar.getTimeInMillis());
			}

		}
	};

	/**
	 * 
	 * Email validation
	 * 
	 * @param email
	 * @return
	 */

	private boolean isEmailValid(String email) {
		boolean result = false;

		if (email != null) {
			Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
			Matcher matcher = pattern.matcher(email);
			result = matcher.matches();
		}
		return result;
	}

	/** Validate credentials provided */
	private boolean validate(EditText credential) {
		boolean ret = !(credential == null || credential.getText() == null || TextUtils.isEmpty(credential.getText().toString().trim()));
		return ret;
	}
}
